package homepage

import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Lock
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.VerticalAlignmentLine
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import entity.User
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlin.reflect.KProperty

@Composable
fun homepage() {
  return Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize(), content = {

    val state = remember(calculation = { mutableStateMapOf("username" to "", "password" to "") })
    val hostState = SnackbarHostState()
    val host = SnackbarHost(hostState = hostState, snackbar = {
      Snackbar(snackbarData = it, actionOnNewLine = true)
    })

    makeCenteredRow {
      mainCard(state, hostState)
    }
  })
}

@Composable
fun mainCard(state: SnapshotStateMap<String, String>, hostState: SnackbarHostState) {
  return Card(elevation = 8.dp, content = {
    Column(horizontalAlignment = Alignment.CenterHorizontally, content = {
      makeCenteredRow {
        makeTextFiled(
          name = "username",
          leadingIcon = { Icon(Icons.Default.AccountCircle, "") },
          state = state
        )
      }
      makeCenteredRow {
        makeTextFiled(
          name = "password",
          leadingIcon = { Icon(Icons.Default.Lock, "") },
          state = state
        )
      }
      makeCenteredRow {
        Button(content = { Text("Check") }, onClick = {
          snackOut(User(state.getValue("username"),state.getValue("password")).toString(), hostState)
        })
      }
    })
  })
}

@Composable
fun makeTextFiled(
  name: String,
  key: String = name,
  leadingIcon: @Composable () -> Unit,
  state: SnapshotStateMap<String, String>,
  onValueChange: (String) -> Unit = {
    state[key] = it
  }
) {
  return TextField(
    value = state.getValue(key),
    leadingIcon = leadingIcon,
    onValueChange = onValueChange,
    singleLine = true,
    label = { Text(name) },
    placeholder = { Text("Input your $name here") }
  )
}

fun snackOut(message: String, hostState: SnackbarHostState) {
  GlobalScope.launch {
    coroutineScope {
      hostState.showSnackbar(message, "Okay")
    }
  }
}

@Composable
fun makeCenteredRow(content: @Composable RowScope.() -> Unit) {
  return Row(
    modifier = Modifier.padding(16.dp),
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = Arrangement.Center,
    content = content
  )
}
